//自定义封装pthread的mutex 互斥量类似于java的锁

#ifndef MUTEX_H
#define MUTEX_H


#include <pthread.h>
#include <stdint.h>
#include <time.h>
#include <sys/types.h>

//uint32_t 无符号32bit 就是unsigned int 
typedef uint32_t status_t;		 

class Condition;			//不明白这是为何

class Mutex {
	public:
		enum {
			PRIVATE 0,
			SHARED = 1
		};
		Mutex();
		Mutex(const char* name);
		Mutex(int type, const char* name = NULL);
		~Mutex();

		//互斥量锁 会阻塞线程
		status_t lock();
		void unclock();
		
		//trylock 不会阻塞线程，失败会立即返回错误码
		status_t tryLock();
		/**
		* Mutex的自动管理类，获取时自动上锁，离开时自动释放锁
		*/
		class AutoLock{
			private:
				Mutex& mLock;
			public:
				inline AutoLock(Mutex& mutex):mLock(mutex) {mLock.lock();}
				inline AutoLock(Mutex* mutex):mLock(*mutex) {mLock.lock();}
				inline ~AutoLock() {mLock.unlock()};
		};

	private:
		friend class Condition;
		Mutex(const Mutex&);
		Mutex& operator = (const Mutex&);

		pthread_mutex_t mMutex;

};


inline Mutex::Mutex(){
	pthread_mutex_init(&mMutex, NULL);
}

inline Mutex::Mutex(const char * name){
	pthread_mutex_init(&mMutex, name);
}

inline Mutex:Mutex(int type, const char* name){
	if(type == SHARED){
		//设置互斥量共享
		pthread_mutexattr_t attr;
		pthread_mutexattr_init(&attr);
		pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
		pthread_mutex_init(&mMutex, &attr);
		pthread_mutexattr_destroy(&attr);
	}else{
		pthread_mutex_init(&mMutex, NULL);
	}
}

inline Mutex::~Mutex(){
	pthread_mutex_destroy(&mMutex);
}

inline status_t Mutex::lock(){
	return -pthread_mutex_lock(&mMutex);
}

inline status_t Mutex::tryLock(){
	return -pthread_mutex_trylock(&mMutex);
}

inline void Mutex::unlock(){
	pthread_mutex_unlock(&mMutex);
}

typedef Mutex::Autolock AutoMutex;
#endif
